package cn.kgc.vue.controller;

import cn.hutool.crypto.digest.MD5;
import cn.kgc.vue.commons.*;
import cn.kgc.vue.entity.User;
import cn.kgc.vue.form.LoginFrom;
import cn.kgc.vue.form.PasswordForm;
import cn.kgc.vue.form.UserForm;
import cn.kgc.vue.service.UserService;
import cn.kgc.vue.utils.JWTUtil;
import cn.kgc.vue.utils.SaltUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;

/**
 * @author 课工场
 * @date 2023/12/2
 * @description
 */
@RestController
@RequestMapping("users")
@Api(tags = "用户模块")
@Slf4j
public class UserController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserService userService;

    @Resource
    private JWTUtil jwtUtil;

    // 登录
    @ApiOperation("用户认证")
    @PostMapping("login")
    public ResponseResult login(@RequestBody LoginFrom loginFrom, HttpServletRequest request) {

        return userService.login(loginFrom, request);
    }

    @ApiOperation("用户列表")
    @PostMapping("/list")
    public ResponseResult userList(@RequestBody QueryCondition<User> queryCondition) {

        return userService.userList(queryCondition);
    }



    @KgcLogs(model = "用户模块",operation = KgcOperation.DELETE)
    @RequiresPermissions("sys:user:delete")
    @ApiOperation("删除用户")
    @DeleteMapping
    public ResponseResult delete(@RequestBody Integer[] uids) {

        return userService.batchRemoveByIds(Arrays.asList(uids));
    }


    @KgcLogs(model = "用户模块",operation = KgcOperation.UPDATE)
    @ApiOperation("编辑用户状态")
    @RequiresPermissions("sys:user:update")
    @PutMapping("state")
    public ResponseResult editState(@RequestBody User user) {
        userService.updateById(user);
        return ResponseResult.success().message("状态更新成功");
    }


    @KgcLogs(model = "用户模块",operation = KgcOperation.ADD)
    @ApiOperation("添加用户")
    @RequiresPermissions("sys:user:add")
    @PostMapping
    public ResponseResult addUser(@RequestBody UserForm userForm) {
        return userService.saveUser(userForm);
    }


    @ApiOperation("重置密码")
    @PutMapping("resetPwd/{uid}")
    @RequiresPermissions("sys:user:update")
    public ResponseResult resetPwd(@PathVariable Integer uid) {
        User user = new User();
        user.setId(uid);

        String salt = SaltUtil.createSalt(8);
        user.setSalt(salt);

        String hex = new Md5Hash("666666", salt, 1024).toHex();
        user.setPassword(hex);

        userService.updateById(user);
        return ResponseResult.success().message("密码重置成功");
    }


    @ApiOperation("根据id获取用户信息")
    @GetMapping("{uid}")
    public ResponseResult getUserById(@PathVariable Integer uid) {

        return userService.getUserById(uid);
    }


    @KgcLogs(model = "用户模块",operation = KgcOperation.UPDATE)
    @ApiOperation("修改用户信息")
    @PutMapping("editUser")
    @RequiresPermissions("sys:user:update")
    public ResponseResult editUser(@RequestBody UserForm userForm) {

        return userService.editUser(userForm);
    }

    @ApiOperation("获取个人资料")
    @GetMapping("personalInfo")
    public ResponseResult getPersonalInfo(HttpServletRequest request) {

        String token = request.getHeader("token");
        Map<String, Object> claims = jwtUtil.getClaims(token);
        Integer uid = (Integer) claims.get("uid");

        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getId,uid)
                .select(User::getNickName,User::getSex,User::getCity,User::getTel,User::getId);
        User one = userService.getOne(lambda);

        return ResponseResult.success().data(one);
    }


    @KgcLogs(model = "用户模块",operation = KgcOperation.UPDATE)
    @ApiOperation("编辑个人资料")
    @PutMapping("editPersonalInfo")
    public ResponseResult editPersonalInfo( @RequestBody UserForm userForm) {

        userService.updateById(userForm);

        return ResponseResult.success().message("编辑成功");
    }

    @ApiOperation("编辑个人密码")
    @PutMapping("editPersonalPassword")
    public ResponseResult editPersonalPassword(@RequestBody PasswordForm passwordForm,HttpServletRequest request) {


        return userService.editPersonalPassword(passwordForm,request);
    }


    @ApiOperation("安全退出")
    @GetMapping("logout")
    public ResponseResult logout(HttpServletRequest request) {

        String token = request.getHeader("token");

        stringRedisTemplate.delete(MD5.create().digestHex(token));

        return ResponseResult.success().message("安全退出");
    }


    @ApiOperation("获取用户权限")
    @GetMapping("permissions")
    public ResponseResult getUserPermission(HttpServletRequest request) {

        String token = request.getHeader("token");
        Integer uid = (Integer) jwtUtil.getClaims(token).get("uid");


        return userService.getUserPermission(uid);
    }


    @GetMapping("authenticate")
    public ResponseResult noAuthenticated() {
        return ResponseResult.fail().message(ResultCode.NO_AUTHENTICATED.getMessage()).code(ResultCode.NO_AUTHENTICATED.getCode());
    }

}
